<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="模块名称" v-model="whereQuery.title">
      </el-input>
      <el-select clearable style="width: 90px" class="filter-item" v-model="whereQuery.type" placeholder="分类" @change="handleFilter">
        <el-option v-for="item in sectionTypeOptions" :key="item" :label="item | sectionTypeFilter" :value="item">
        </el-option>
      </el-select>
      <el-select clearable style="width: 110px" class="filter-item" v-model="whereQuery.visible" placeholder="是否展示" @change="handleFilter">
        <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" v-waves @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" v-waves @click="orderSection" icon="el-icon-edit">排序</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%">
      <el-table-column align="center" label="id" width="300">
        <template slot-scope="scope">
          <span class="link-type" style="font-family: Menlo, Monaco, Consolas, Courier New, monospace;" @click="showJsonObject(scope.row)">{{scope.row._id}}</span>
        </template>
      </el-table-column>
      <el-table-column width="135px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createdAt | momentFormat('YYYY-MM-DD HH:mm')}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" header-align="center" label="模块名称">
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column width="80px" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.type | sectionTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column width="50px" align="center" label="排序">
        <template slot-scope="scope">
          <span>{{scope.row.index}}</span>
        </template>
      </el-table-column>
      <el-table-column width="120px" header-align="center" label="列表组" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="link-type" v-if="scope.row.listGroup" @click="showJsonObject(scope.row.listGroup)">{{scope.row.listGroup.name}}</span>
        </template>
      </el-table-column>
      <el-table-column width="50px" align="center" label="行数">
        <template slot-scope="scope">
          <span>{{scope.row.maxRow}}</span>
        </template>
      </el-table-column>
      <el-table-column width="50px" align="center" label="展示">
        <template slot-scope="scope">
          <span v-if="scope.row.visible">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column width="50px" align="center" label="更多">
        <template slot-scope="scope">
          <span v-if="scope.row.more">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog title="对象" :visible.sync="jsonVisible">
      <el-form label-position="right" style='min-width: 600px;'>
        <el-form-item>
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 27}" v-model="jsonObject">
          </el-input>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="排序" :visible.sync="orderVisible" width="70%">
      <div class="components-container">
        <div class="editor-container">
          <dnd-list :list1="list1" :list2="list2" list1Title="已排序" list2Title="待排序"></dnd-list>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="orderVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateOrderSection">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="120px" style='width: 650px; margin-left:20px;'>
        <el-form-item label="模块名称" prop="title">
          <el-input v-model="temp.title"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select class="filter-item" v-model="temp.type" placeholder="请选择">
            <el-option v-for="item in sectionTypeOptions" :key="item" :label="item | sectionTypeFilter" :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="index" :rules="[{pattern: /^\d*$/,message: '排序只能输入整数值'}]">
          <el-input v-model.number="temp.index"></el-input>
        </el-form-item>
        <el-form-item label="列表组(id)">
          <el-col :span="12">
            <el-input style="width: 100%" v-model="temp.listGroup._id"></el-input>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="11">
            <el-select style="width: 100%;" v-model="temp.listGroup._id" clearable filterable remote placeholder="请输入关键词" :remote-method="remoteEditMethod" :loading="editListGroupLoading">
              <el-option v-for="item in groupOptions" :key="item._id" :label="item.name" :value="item._id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="最大展示行数" prop="maxRow" :rules="[{pattern: /^\d*$/,message: '最大展示行数只能输入整数值'}]">
          <el-input v-model.number="temp.maxRow"></el-input>
        </el-form-item>
        <el-form-item label="是否展示">
          <el-select class="filter-item" v-model="temp.visible" placeholder="请选择">
            <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否有更多选项">
          <el-select class="filter-item" v-model="temp.more" placeholder="请选择">
            <el-option v-for="item in booleanOptions" :key="item.key" :label="item.value" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确 定</el-button>
        <el-button v-else type="primary" @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { fetch, insert, deleteById, update, cloud } from '@/api/jb'
  import waves from '@/directive/waves' // 水波纹指令
  import { MessageBox } from 'element-ui'
  import DndList from '@/components/DndList'

  const booleanOptions = [
    { key: true, value: '是' },
    { key: false, value: '否' }
  ]

  export default {
    name: 'section',
    components: { DndList },
    directives: {
      waves
    },
    data() {
      return {
        list1: [],
        list2: [],
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          skip: 0,
          limit: 10,
          include: 'listGroup',
          where: {
            title: {
              $regex: '.*'
            },
            type: undefined,
            visible: undefined
          },
          count: true,
          order: {
            visible: -1,
            index: 1,
            updatedAt: -1
          }
        },
        whereQuery: {
          title: undefined,
          type: undefined,
          visible: undefined
        },
        sectionTypeOptions: [1, 2, 3, 4],
        groupOptions: [],
        editListGroupLoading: false,
        booleanOptions,
        sortOptions: [{ label: '按ID升序列', key: '+id' }, { label: '按ID降序', key: '-id' }],
        temp: {
          _id: undefined,
          title: undefined,
          type: 1,
          index: undefined,
          listGroup: {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          },
          visible: false,
          maxRow: 1,
          more: false
        },
        dialogFormVisible: false,
        jsonVisible: false,
        orderVisible: false,
        jsonObject: undefined,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          title: [{ required: true, message: '模块名称不能为空', trigger: 'change' }],
          type: [{ required: true, message: '类型 is required', trigger: 'change' }]
        }
      }
    },
    filters: {
      sectionTypeFilter(type) {
        const sectionType = ['轮播图', '四图', '五图', '长图']
        return type > 0 ? sectionType[type - 1] : ''
      },
      json: (value) => { return JSON.stringify(value, null, 2) }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        fetch('Section', this.listQuery).then(response => {
          this.list = response.data.data.result
          this.total = response.data.data.count
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.skip = 0
        if (this.whereQuery.title) {
          this.listQuery.where.title.$regex = '.*' + this.whereQuery.title + '.*'
        } else {
          this.listQuery.where.title = undefined
        }
        if (this.whereQuery.type) {
          this.listQuery.where.type = this.whereQuery.type
        } else {
          this.listQuery.where.type = undefined
        }
        if (this.whereQuery.visible === '') {
          this.listQuery.where.visible = undefined
        } else {
          this.listQuery.where.visible = this.whereQuery.visible
        }
        this.getList()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.skip = (val - 1) * this.listQuery.limit
        this.getList()
      },
      resetTemp() {
        this.temp = {
          _id: undefined,
          title: undefined,
          type: 1,
          index: undefined,
          listGroup: {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          },
          visible: false,
          maxRow: 1,
          more: false
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.groupOptions = []
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.listGroup._id) {
              tempData.listGroup = undefined
            }
            insert('Section', tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.listQuery.skip = 0
              this.getList()
            })
          }
        })
      },
      handleUpdate(row) {
        for (const key of Reflect.ownKeys(this.temp)) {
          this.temp[key] = row[key]
        }
        if (!this.temp.listGroup) {
          this.temp.listGroup = {
            _id: undefined,
            __type: 'Pointer',
            className: 'ListGroup'
          }
        } else {
          this.groupOptions = [{
            '_id': row.listGroup._id,
            'name': row.listGroup.name
          }]
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            if (!this.temp.listGroup || !this.temp.listGroup._id) {
              tempData.listGroup = undefined
            }
            update('Section', this.temp._id, tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            })
          }
        })
      },
      orderSection() {
        this.orderVisible = true
        this.list1 = []
        this.list2 = []
        const orderQuery = {
          order: {
            index: 1,
            updatedAt: -1
          }
        }
        fetch('Section', orderQuery).then(response => {
          const list = response.data.data.result
          for (const item in list) {
            if (list[item].visible) {
              this.list1.push(list[item])
            } else {
              this.list2.push(list[item])
            }
          }
        })
      },
      updateOrderSection() {
        var sectionIds = ''
        for (const item of this.list1) {
          sectionIds += item._id + ','
        }
        const parmas = {
          'sectionIds': sectionIds
        }
        cloud('updateSectionIndex', parmas).then(response => {
          if (response.data.code === 0) {
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success',
              duration: 2000
            })
            this.orderVisible = false
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: response.data.message,
              type: 'info',
              duration: 2000
            })
          }
        })
      },
      remoteEditMethod(keyword) {
        if (this.editListGroupLoading) {
          return
        }
        if (keyword !== '') {
          this.editListGroupLoading = true
          setTimeout(() => {
            this.editListGroupLoading = false
            const query = {
              limit: 10,
              keys: ['_id', 'name'],
              where: {
                name: {
                  $regex: '.*' + keyword + '.*'
                }
              }
            }
            fetch('ListGroup', query).then(response => {
              this.groupOptions = response.data.data.result
            })
          }, 200)
        } else {
          this.groupOptions = []
        }
      },
      handleDelete(row) {
        MessageBox.confirm('是否确认删除？', '确定删除', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteById('Section', row._id).then(response => {
            if (response.data.code === 0) {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            } else {
              this.$notify({
                title: '失败',
                message: response.data.message,
                type: 'info',
                duration: 2000
              })
            }
          })
        })
      },
      showJsonObject(data) {
        this.jsonVisible = true
        this.jsonObject = JSON.stringify(data, null, 4)
      }
    }
  }
</script>
